package com.taoyibao.hongcanting.http.interceptor;

import com.taoyibao.hongcanting.constant.NetCode;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Token刷新
 */

public class TokenInterceptor implements Interceptor {
    private static final String TAG = "TokenInterceptor";

    @Override
    public Response intercept(Chain chain) throws IOException {
        synchronized (this) {
            Request request = chain.request();
            Response response = chain.proceed(request);
            if (isTokenExpired(response)) {//根据和服务端的约定判断token过期
                //同步请求方式，获取最新的Token
                String newSession = getNewToken();
                //使用新的Token，创建新的请求
                Request newRequest = chain.request()
                        .newBuilder()
                        .header("token", newSession)
                        .build();
                //重新请求
                return chain.proceed(newRequest);
            }
            return response;
        }
    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response) {
        if (response.code() == NetCode.HTTP_300) {
            return true;
        }
        return false;
    }

    /**
     * 同步请求方式，获取最新的Token
     *
     * @return
     */
    private String getNewToken() throws IOException {
        // 通过一个特定的接口获取新的token，此处要用到同步的retrofit请求
//        String refreshToken = LoginUtil.getRefreshToken();
//        Call<TokenModel> call = JsonApiWrapper.getApiService().refreshToken(refreshToken);
//        TokenModel body = call.execute().body();
//        if (body.status == Keys.HTTP_20000) {
//            LogUtils.eNormal(TAG, "同步请求刷新成功token:" + body.status);
//            LoginUtil.putToken(body.token);
//            return body.token;
//        } else {
//            LogUtils.eNormal(TAG, "同步请求刷新失败token:" + body.status);
//            RxBus.getDefault().post(new RxBus_GoLogin());
//            return "";
//        }
        return "";
    }
}
